package util

import (
	"archive/zip"
	// "bytes"
	// "encoding/xml"
	"fmt"
	"io"
	"log"
	"strings"

	//"github.com/groob/plist"
	"howett.net/plist"
)

// IpaInfo 存储提取的信息
type IpaInfo struct {
	BundleID      string `plist:"CFBundleIdentifier"`
	BundleVersion string `plist:"CFBundleShortVersionString"`
	BuildVersion  string `plist:"CFBundleVersion"`
}

type PlistDict struct {
	Keys   []string `xml:"key"`
	Values []string `xml:"string"`
}

type Plist struct {
	Dict PlistDict `xml:"dict"`
}

// ExtractIPAInfo 从 .ipa 文件中提取 Bundle ID 和版本信息
func ExtractIPAInfo(ipaPath string) (*IpaInfo, error) {
	// 打开 .ipa 文件（本质是 ZIP）
	r, err := zip.OpenReader(ipaPath)
	if err != nil {
		log.Printf("打开ipa文件失败: %v", err)
		return nil, fmt.Errorf("failed to open ipa file: %v", err)
	}
	defer r.Close()

	// 查找 Payload/*.app/Info.plist
	var plistContent []byte
	for _, f := range r.File {
		if strings.Contains(f.Name, ".app/Info.plist") {
			rc, err := f.Open()
			if err != nil {
				log.Printf("打开Info.plist文件失败: %v", err)
				return nil, fmt.Errorf("failed to open Info.plist: %v", err)
			}
			defer rc.Close()

			plistContent, err = io.ReadAll(rc)
			if err != nil {
				log.Printf("读取Info.plist文件失败: %v", err)
				return nil, fmt.Errorf("failed to read Info.plist: %v", err)
			}
			break
		}
	}

	if len(plistContent) == 0 {
		log.Println("未能找到Info.plist文件")
		return nil, fmt.Errorf("Info.plist not found in ipa")
	}

	info := &IpaInfo{}
	if _, err := plist.Unmarshal(plistContent, info); err != nil {
		log.Printf("Info.plist文件格式错误: %v", err)
		return nil, fmt.Errorf("failed to parse plist: %v", err)
	}

	return info, nil
}
